import matplotlib.pyplot as plt
import numpy as np
import time

# flag = 1 # Giou
flag = 0 # Liou

def calculate_iou(pred, target, pred_width, target_width):
    px1 = pred - pred_width
    px2 = pred + pred_width
    tx1 = target - target_width
    tx2 = target + target_width

    # 计算交集
    inter_x1 = max(px1, tx1)
    inter_x2 = min(px2, tx2)
    inter = inter_x2 - inter_x1

    # 计算并集
    union_x1 = min(px1, tx1)
    union_x2 = max(px2, tx2)
    union = union_x2 - union_x1

    if flag == 1:
        G = np.clip((union - 2 * (target_width + pred_width)) / (union + 1e-9), a_min=0., a_max=1.)
    else :
        G = 0
    # 计算IoU
    iou = inter / (union +1e-9) - G
    return iou,inter,union,G

# 参数设置
width = 2
pred_width = width / 3.14
target_width = width / 3.14
target = 0 # 目标中心点位置固定为0
T1 = time.time()

# 遍历pred从-80到80
preds = np.linspace(-80, 80, 161)  # 161个点，包括-80和80
ious, inters, unions, Gs = zip(*[calculate_iou(pred, target, pred_width, target_width) for pred in preds])
# 计算1 - iou
one_minus_ious = [(1 - iou)*4.0 for iou in ious]
test = [ 1 - one_minus_iou / 8.0 for one_minus_iou in one_minus_ious]
Gs = [ -1 * ( G + 1) for G in Gs]
T2 = time.time()
print('程序运行时间:%s毫秒' % ((T2 - T1)*1000))

# 绘图
plt.figure(figsize=(10, 6))
# plt.plot(preds, one_minus_ious, marker='o', label='1 - IoU')
plt.plot(preds, ious, marker='o', label='IoU')
plt.plot(preds, test, marker='x', label='test')
# plt.plot(preds, inters, marker='x', label='Intersection')
# plt.plot(preds, unions, marker='s', label='Union')
plt.plot(preds, Gs, marker='o', label='G')
plt.title('1 - IoU, Intersection, and Union vs Prediction Offset')
plt.xlabel('Prediction Offset')
plt.ylabel('Values')
# 限制y轴范围
plt.xlim(-20, 20)
# plt.ylim(-1.25,1)
plt.legend()
plt.grid(True)
plt.show()